using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Resource.@string;
using MicroMsg.Storage;
using MicroMsgBackground.Manager;
using Microsoft.Phone.Scheduler;
using System;
using System.IO.IsolatedStorage;
namespace MicroMsg.Scene
{
	public class BackgroundService
	{
		private const string TAG = "BackgroundService";
		private static PeriodicTask periodicTask;
		private static string periodicTaskName = "MicroMsgPeriodicAgent";
		public static void StartPeriodicAgent()
		{
			BackgroundService.periodicTask = (ScheduledActionService.Find(BackgroundService.periodicTaskName) as PeriodicTask);
			if (BackgroundService.periodicTask != null)
			{
				BackgroundService.StopPeriodicAgent();
			}
			if (!GConfigMgr.getBool("BackgroundServiceOn", true))
			{
				Log.smethod_5("BackgroundService", "Background agents for this application have been disabled by the user. BackgroundServiceOn is off");
				return;
			}
			BackgroundService.periodicTask = new PeriodicTask(BackgroundService.periodicTaskName);
			BackgroundService.periodicTask.set_Description(strings.Background_Task_Description);
			try
			{
				ScheduledActionService.Add(BackgroundService.periodicTask);
				BackgroundService.saveBackgroundAccout();
			}
			catch (InvalidOperationException ex)
			{
				if (ex.get_Message().Contains("BNS Error: The action is disabled"))
				{
					Log.smethod_5("BackgroundService", "Background agents for this application have been disabled by the user.");
				}
				ex.get_Message().Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
			}
			catch (SchedulerServiceException)
			{
			}
		}
		public static void StopPeriodicAgent()
		{
			try
			{
				ScheduledActionService.Remove(BackgroundService.periodicTaskName);
			}
			catch (Exception)
			{
			}
		}
		private static void saveBackgroundAccout()
		{
			Account curAccount = MicroMsg.Manager.AccountMgr.getCurAccount();
			AccountBackground accountBackground = new AccountBackground();
			accountBackground.strUsrName = curAccount.strUsrName;
			accountBackground.strPwd = curAccount.strPwd;
			accountBackground.strPwd2 = curAccount.strPwd2;
			accountBackground.nUin = curAccount.nUin;
			accountBackground.currentLanguage = MicroMsg.Manager.AccountMgr.GetCurrentLanguage();
			accountBackground.bytesSessionkey = curAccount.bytesSessionkey;
			accountBackground.bytesCurSyncKey = curAccount.bytesCurSyncKey;
			accountBackground.bytesMaxSyncKey = curAccount.bytesMaxSyncKey;
			accountBackground.bytesSyncKeyBuf = curAccount.bytesSyncKeyBuf;
			string text = "background";
			string xmlFilePath = "background/accountinfo.xml";
			using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
			{
				if (!userStoreForApplication.DirectoryExists(text))
				{
					userStoreForApplication.CreateDirectory(text);
				}
			}
			StorageXml.saveToFile<AccountBackground>(accountBackground, xmlFilePath);
		}
	}
}
